package com.ashin.testshardingsphere.service.impl;

import com.ashin.testshardingsphere.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Random;

/**
 * @author Ashin
 */
@Service
public class UserServiceImpl implements UserService {


    @Resource
    private DataSource dataSource;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Object> insertData() throws SQLException {
        System.out.println(dataSource);
        System.out.println(jdbcTemplate);


        // 获取数据库连接
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("insert into orders(id,customer_id,num,price) values(?,?,?,?)");
        for (int i = 0; i < 10; i++) {
            System.out.println("插入的数据id:" + i);
            preparedStatement.setLong(1, i);
            preparedStatement.setLong(2, i);
            preparedStatement.setInt(3, new Random().nextInt(10));
            preparedStatement.setDouble(4, i * 100.0);
            preparedStatement.execute();
        }

        connection.close();
        return null;
    }
}
